// localStorage key: 'weightRecords', value: [{date: '2024-06-01', weight: 70.2}, ...]
// localStorage key: 'points', value: 100
// localStorage key: 'level', value: 2
// localStorage key: 'sportRecords', value: [{date, type, duration, distance, intensity, calories}]

// 全局变量
let currentExchangeItemId = null;

// 全局函数 - 处理确认兑换
window.handleConfirmExchange = function() {
  if (!currentExchangeItemId) {
    showToast('兑换信息错误');
    return;
  }
  
  confirmExchange(currentExchangeItemId);
};

// 全局测试函数 - 测试确认按钮
window.testConfirmButton = function() {
  const confirmBtn = document.getElementById('confirmExchangeBtn');
  if (confirmBtn) {
    handleConfirmExchange();
  }
}

// 全局测试函数 - 直接点击按钮
window.clickConfirmButton = function() {
  const confirmBtn = document.getElementById('confirmExchangeBtn');
  if (confirmBtn) {
    confirmBtn.click();
  }
}



// 运动类型配置
const SPORT_TYPES = {
  '跑步': {
    icon: '🏃‍♂️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 8, '中强度': 12, '高强度': 16 }, // 每分钟消耗卡路里
    description: '有氧运动，提升心肺功能'
  },
  '骑行': {
    icon: '🚴‍♂️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 6, '中强度': 10, '高强度': 14 },
    description: '户外骑行，锻炼腿部肌肉'
  },
  '游泳': {
    icon: '🏊‍♂️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 10, '中强度': 14, '高强度': 18 },
    description: '全身运动，消耗热量高'
  },
  '健身': {
    icon: '💪',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 5, '中强度': 8, '高强度': 12 },
    description: '力量训练，增肌塑形'
  },
  '瑜伽': {
    icon: '🧘‍♀️',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 3, '中强度': 5, '高强度': 8 },
    description: '柔韧性训练，放松身心'
  },
  '跳绳': {
    icon: '⏰',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 8, '中强度': 12, '高强度': 16 },
    description: '高效燃脂，提升协调性'
  },
  '篮球': {
    icon: '🏀',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 7, '中强度': 11, '高强度': 15 },
    description: '团队运动，提升爆发力'
  },
  '足球': {
    icon: '⚽',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 7, '中强度': 11, '高强度': 15 },
    description: '团队运动，锻炼耐力'
  },
  '羽毛球': {
    icon: '🏸',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 6, '中强度': 10, '高强度': 14 },
    description: '技巧性运动，提升反应'
  },
  '网球': {
    icon: '🎾',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 7, '中强度': 11, '高强度': 15 },
    description: '全身协调，提升力量'
  },
  '乒乓球': {
    icon: '🏓',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 4, '中强度': 7, '高强度': 10 },
    description: '技巧性运动，锻炼眼手协调'
  },
  '爬山': {
    icon: '⛰️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 8, '中强度': 12, '高强度': 16 },
    description: '户外运动，锻炼腿部力量'
  },
  '快走': {
    icon: '🚶‍♂️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 4, '中强度': 6, '高强度': 8 },
    description: '有氧运动，适合初学者'
  },
  '慢走': {
    icon: '🚶‍♀️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 2, '中强度': 4, '高强度': 6 },
    description: '轻度运动，恢复训练'
  },
  '跳舞': {
    icon: '💃',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 5, '中强度': 8, '高强度': 12 },
    description: '有氧舞蹈，提升协调性'
  },
  '拳击': {
    icon: '🥊',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 8, '中强度': 12, '高强度': 16 },
    description: '高强度训练，提升爆发力'
  },
  '跆拳道': {
    icon: '🥋',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 7, '中强度': 11, '高强度': 15 },
    description: '武术训练，提升灵活性'
  },
  '滑板': {
    icon: '🛹',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 4, '中强度': 7, '高强度': 10 },
    description: '极限运动，提升平衡感'
  },
  '轮滑': {
    icon: '⛸️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 5, '中强度': 8, '高强度': 12 },
    description: '有氧运动，锻炼腿部'
  },
  '滑雪': {
    icon: '⛷️',
    hasDistance: true,
    hasIntensity: true,
    calorieRate: { '低强度': 6, '中强度': 10, '高强度': 14 },
    description: '冬季运动，全身锻炼'
  },
  '高尔夫': {
    icon: '⛳',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 3, '中强度': 5, '高强度': 8 },
    description: '休闲运动，提升专注力'
  },
  '保龄球': {
    icon: '🎳',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 2, '中强度': 4, '高强度': 6 },
    description: '休闲运动，锻炼手臂'
  },
  '台球': {
    icon: '🎱',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 2, '中强度': 3, '高强度': 5 },
    description: '技巧运动，提升专注力'
  },
  '仰卧起坐': {
    icon: '💪',
    hasDistance: false,
    hasCount: true,
    hasIntensity: true,
    calorieRate: { '低强度': 3, '中强度': 5, '高强度': 8 },
    description: '腹部训练，增强核心力量'
  },
  '俯卧撑': {
    icon: '🏋️',
    hasDistance: false,
    hasCount: true,
    hasIntensity: true,
    calorieRate: { '低强度': 4, '中强度': 6, '高强度': 10 },
    description: '上肢力量训练，锻炼胸肌'
  },
  '深蹲': {
    icon: '🦵',
    hasDistance: false,
    hasCount: true,
    hasIntensity: true,
    calorieRate: { '低强度': 3, '中强度': 5, '高强度': 8 },
    description: '下肢力量训练，锻炼大腿'
  },
  '平板支撑': {
    icon: '🧘',
    hasDistance: false,
    hasCount: false,
    hasIntensity: true,
    calorieRate: { '低强度': 2, '中强度': 4, '高强度': 6 },
    description: '核心稳定训练，增强腹部'
  },
  '引体向上': {
    icon: '🏋️‍♂️',
    hasDistance: false,
    hasCount: true,
    hasIntensity: true,
    calorieRate: { '低强度': 5, '中强度': 8, '高强度': 12 },
    description: '背部力量训练，锻炼背肌'
  },
  '铃壶': {
    icon: '🏋️',
    hasDistance: false,
    hasCount: true,
    hasIntensity: true,
    calorieRate: { '低强度': 6, '中强度': 9, '高强度': 14 },
    description: '全身力量训练，提升爆发力'
  },
  '其他': {
    icon: '🎯',
    hasDistance: false,
    hasIntensity: true,
    calorieRate: { '低强度': 4, '中强度': 7, '高强度': 10 },
    description: '自定义运动类型'
  }
};

const POINTS_PER_KG = 10; // 每减1kg获得10积分
const LEVEL_UP_POINTS = 50; // 每50积分升一级

// 成就奖励积分
const ACHIEVEMENT_REWARDS = {
  'first_record': 10,
  'first_sport': 10,
  'week_streak': 20,
  'month_streak': 50,
  'sport_week': 30,
  'weight_loss_3kg': 30,
  'weight_loss_5kg': 50,
  'weight_loss_10kg': 100,
  'level_3': 20,
  'level_5': 50,
  'level_10': 100,
  'sport_10': 20,
  'sport_50': 50,
  'sport_100': 100,
  'sport_variety': 30,
  'sport_calories': 40,
  'perfect_week': 60,
  'weight_stable': 25,
  'sport_streak': 35
};

// 兑换商品数据
const EXCHANGE_ITEMS = [
  // 美食类
  { id: 'rest_day', name: '休息一天', desc: '今天可以不运动，好好休息', cost: 50, category: 'rest', icon: 'fas fa-bed' },
  { id: 'bbq_meal', name: '吃一顿烤串', desc: '奖励自己一顿美味的烤串', cost: 100, category: 'food', icon: 'fas fa-drumstick-bite' },
  { id: 'ice_cream', name: '冰淇淋', desc: '享受一份美味的冰淇淋', cost: 30, category: 'food', icon: 'fas fa-ice-cream' },
  { id: 'pizza', name: '披萨', desc: '来一份香喷喷的披萨', cost: 80, category: 'food', icon: 'fas fa-pizza-slice' },
  { id: 'chocolate', name: '巧克力', desc: '甜蜜的巧克力奖励', cost: 20, category: 'food', icon: 'fas fa-candy-cane' },
  { id: 'coffee', name: '咖啡', desc: '享受一杯香浓咖啡', cost: 25, category: 'food', icon: 'fas fa-coffee' },
  { id: 'cake', name: '蛋糕', desc: '美味的蛋糕甜点', cost: 60, category: 'food', icon: 'fas fa-birthday-cake' },
  { id: 'noodles', name: '拉面', desc: '来一碗热腾腾的拉面', cost: 40, category: 'food', icon: 'fas fa-utensils' },
  { id: 'sushi', name: '寿司', desc: '精致的日式寿司', cost: 120, category: 'food', icon: 'fas fa-fish' },
  { id: 'hotpot', name: '火锅', desc: '和朋友一起吃火锅', cost: 150, category: 'food', icon: 'fas fa-fire' },
  
  // 休息类
  { id: 'sleep_in', name: '睡懒觉', desc: '周末可以多睡一会儿', cost: 40, category: 'rest', icon: 'fas fa-moon' },
  { id: 'movie', name: '看电影', desc: '看一部喜欢的电影', cost: 35, category: 'rest', icon: 'fas fa-film' },
  { id: 'massage', name: '按摩', desc: '享受一次放松按摩', cost: 200, category: 'rest', icon: 'fas fa-hands' },
  { id: 'bath', name: '泡澡', desc: '泡个舒服的热水澡', cost: 30, category: 'rest', icon: 'fas fa-bath' },
  { id: 'reading', name: '看书', desc: '安静地看会儿书', cost: 25, category: 'rest', icon: 'fas fa-book' },
  { id: 'music', name: '听音乐', desc: '听喜欢的音乐放松', cost: 15, category: 'rest', icon: 'fas fa-music' },
  { id: 'gaming', name: '打游戏', desc: '玩一会儿喜欢的游戏', cost: 45, category: 'rest', icon: 'fas fa-gamepad' },
  { id: 'walk', name: '散步', desc: '悠闲地散个步', cost: 20, category: 'rest', icon: 'fas fa-walking' },
  
  // 奖励类
  { id: 'new_clothes', name: '新衣服', desc: '买一件新衣服奖励自己', cost: 300, category: 'reward', icon: 'fas fa-tshirt' },
  { id: 'shoes', name: '新鞋子', desc: '买一双舒适的运动鞋', cost: 400, category: 'reward', icon: 'fas fa-shoe-prints' },
  { id: 'gym_member', name: '健身房会员', desc: '办理健身房会员卡', cost: 800, category: 'reward', icon: 'fas fa-dumbbell' },
  { id: 'yoga_class', name: '瑜伽课', desc: '参加一节瑜伽课程', cost: 150, category: 'reward', icon: 'fas fa-pray' },
  { id: 'swimming', name: '游泳', desc: '去游泳馆游泳', cost: 100, category: 'reward', icon: 'fas fa-swimming-pool' },
  { id: 'travel', name: '短途旅行', desc: '来一次短途旅行', cost: 1000, category: 'reward', icon: 'fas fa-plane' },
  { id: 'spa', name: 'SPA', desc: '享受一次SPA护理', cost: 500, category: 'reward', icon: 'fas fa-spa' },
  { id: 'concert', name: '演唱会', desc: '看一场喜欢的演唱会', cost: 600, category: 'reward', icon: 'fas fa-microphone' },
  { id: 'book', name: '买书', desc: '买一本喜欢的书', cost: 80, category: 'reward', icon: 'fas fa-book-open' },
  { id: 'plant', name: '盆栽', desc: '买一盆绿植装饰房间', cost: 120, category: 'reward', icon: 'fas fa-seedling' },
  { id: 'art', name: '绘画', desc: '买一套绘画工具', cost: 200, category: 'reward', icon: 'fas fa-palette' },
  { id: 'camera', name: '相机', desc: '买一台相机记录生活', cost: 1500, category: 'reward', icon: 'fas fa-camera' },
  { id: 'watch', name: '手表', desc: '买一块运动手表', cost: 800, category: 'reward', icon: 'fas fa-clock' },
  { id: 'headphones', name: '耳机', desc: '买一副好耳机', cost: 300, category: 'reward', icon: 'fas fa-headphones' },
  { id: 'laptop', name: '笔记本电脑', desc: '买一台笔记本电脑', cost: 5000, category: 'reward', icon: 'fas fa-laptop' },
  { id: 'phone', name: '手机', desc: '换一部新手机', cost: 3000, category: 'reward', icon: 'fas fa-mobile-alt' },
  { id: 'car', name: '汽车', desc: '买一辆汽车', cost: 100000, category: 'reward', icon: 'fas fa-car' },
  { id: 'house', name: '房子', desc: '买一套房子', cost: 1000000, category: 'reward', icon: 'fas fa-home' }
];

// 成就系统
const ACHIEVEMENTS = [
  // 基础成就
  {
    id: 'first_record',
    title: '初次记录',
    desc: '完成第一次体重记录',
    icon: 'fas fa-star',
    condition: (data) => data.weightRecords.length >= 1
  },
  {
    id: 'first_sport',
    title: '运动达人',
    desc: '完成第一次运动记录',
    icon: 'fas fa-running',
    condition: (data) => data.sportRecords.length >= 1
  },
  
  // 坚持成就
  {
    id: 'week_streak',
    title: '坚持一周',
    desc: '连续记录7天体重',
    icon: 'fas fa-calendar-week',
    condition: (data) => data.weightRecords.length >= 7
  },
  {
    id: 'month_streak',
    title: '坚持一月',
    desc: '连续记录30天体重',
    icon: 'fas fa-calendar-alt',
    condition: (data) => data.weightRecords.length >= 30
  },
  {
    id: 'sport_week',
    title: '运动周',
    desc: '一周内完成7次运动',
    icon: 'fas fa-dumbbell',
    condition: (data) => {
      const weekAgo = new Date();
      weekAgo.setDate(weekAgo.getDate() - 7);
      const weekSports = data.sportRecords.filter(s => new Date(s.date) >= weekAgo);
      return weekSports.length >= 7;
    }
  },
  
  // 减重成就
  {
    id: 'weight_loss_3kg',
    title: '减重3kg',
    desc: '累计减重3公斤',
    icon: 'fas fa-weight',
    condition: (data) => {
      if (data.weightRecords.length < 2) return false;
      const first = data.weightRecords[0];
      const last = data.weightRecords[data.weightRecords.length - 1];
      return (first.weight - last.weight) >= 3;
    }
  },
  {
    id: 'weight_loss_5kg',
    title: '减重5kg',
    desc: '累计减重5公斤',
    icon: 'fas fa-weight',
    condition: (data) => {
      if (data.weightRecords.length < 2) return false;
      const first = data.weightRecords[0];
      const last = data.weightRecords[data.weightRecords.length - 1];
      return (first.weight - last.weight) >= 5;
    }
  },
  {
    id: 'weight_loss_10kg',
    title: '减重10kg',
    desc: '累计减重10公斤',
    icon: 'fas fa-weight',
    condition: (data) => {
      if (data.weightRecords.length < 2) return false;
      const first = data.weightRecords[0];
      const last = data.weightRecords[data.weightRecords.length - 1];
      return (first.weight - last.weight) >= 10;
    }
  },
  
  // 等级成就
  {
    id: 'level_3',
    title: '等级3',
    desc: '达到等级3',
    icon: 'fas fa-trophy',
    condition: (data) => data.level >= 3
  },
  {
    id: 'level_5',
    title: '等级达人',
    desc: '达到等级5',
    icon: 'fas fa-trophy',
    condition: (data) => data.level >= 5
  },
  {
    id: 'level_10',
    title: '等级大师',
    desc: '达到等级10',
    icon: 'fas fa-crown',
    condition: (data) => data.level >= 10
  },
  
  // 运动成就
  {
    id: 'sport_10',
    title: '运动新手',
    desc: '完成10次运动记录',
    icon: 'fas fa-running',
    condition: (data) => data.sportRecords.length >= 10
  },
  {
    id: 'sport_50',
    title: '运动达人',
    desc: '完成50次运动记录',
    icon: 'fas fa-running',
    condition: (data) => data.sportRecords.length >= 50
  },
  {
    id: 'sport_100',
    title: '运动大师',
    desc: '完成100次运动记录',
    icon: 'fas fa-running',
    condition: (data) => data.sportRecords.length >= 100
  },
  {
    id: 'sport_variety',
    title: '运动多样',
    desc: '尝试5种不同运动',
    icon: 'fas fa-list',
    condition: (data) => {
      const types = new Set(data.sportRecords.map(s => s.type));
      return types.size >= 5;
    }
  },
  {
    id: 'sport_calories',
    title: '热量达人',
    desc: '单日消耗500千卡',
    icon: 'fas fa-fire',
    condition: (data) => {
      const today = new Date().toISOString().slice(0, 10);
      const todaySports = data.sportRecords.filter(s => s.date === today);
      const totalCalories = todaySports.reduce((sum, s) => sum + (s.calories || 0), 0);
      return totalCalories >= 500;
    }
  },
  
  // 特殊成就
  {
    id: 'perfect_week',
    title: '完美一周',
    desc: '一周内每天都有体重和运动记录',
    icon: 'fas fa-star',
    condition: (data) => {
      const weekAgo = new Date();
      weekAgo.setDate(weekAgo.getDate() - 7);
      const weekWeightDates = new Set(data.weightRecords
        .filter(r => new Date(r.date) >= weekAgo)
        .map(r => r.date));
      const weekSportDates = new Set(data.sportRecords
        .filter(s => new Date(s.date) >= weekAgo)
        .map(s => s.date));
      
      // 检查最近7天是否每天都有记录
      for (let i = 0; i < 7; i++) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = date.toISOString().slice(0, 10);
        if (!weekWeightDates.has(dateStr) || !weekSportDates.has(dateStr)) {
          return false;
        }
      }
      return true;
    }
  },
  {
    id: 'weight_stable',
    title: '体重稳定',
    desc: '连续7天体重变化不超过1kg',
    icon: 'fas fa-balance-scale',
    condition: (data) => {
      if (data.weightRecords.length < 7) return false;
      const recentRecords = data.weightRecords.slice(-7);
      const weights = recentRecords.map(r => r.weight);
      const maxWeight = Math.max(...weights);
      const minWeight = Math.min(...weights);
      return (maxWeight - minWeight) <= 1;
    }
  },
  {
    id: 'sport_streak',
    title: '运动连续',
    desc: '连续7天都有运动记录',
    icon: 'fas fa-calendar-check',
    condition: (data) => {
      const weekAgo = new Date();
      weekAgo.setDate(weekAgo.getDate() - 7);
      const weekSports = data.sportRecords.filter(s => new Date(s.date) >= weekAgo);
      const sportDates = new Set(weekSports.map(s => s.date));
      
      // 检查最近7天是否每天都有运动
      for (let i = 0; i < 7; i++) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = date.toISOString().slice(0, 10);
        if (!sportDates.has(dateStr)) {
          return false;
        }
      }
      return true;
    }
  }
];

// 开屏动画
function initSplashScreen() {
  const splashScreen = document.getElementById('splashScreen');
  const appContainer = document.getElementById('appContainer');
  
  // 模拟加载时间
  setTimeout(() => {
    splashScreen.style.opacity = '0';
    splashScreen.style.transform = 'scale(0.95)';
    
    setTimeout(() => {
      splashScreen.style.display = 'none';
      appContainer.classList.add('show');
      showPage('homePage');
    }, 300);
  }, 2000);
}

// 页面切换
function showPage(pageId) {
  // 隐藏所有页面
  const pages = document.querySelectorAll('.page');
  pages.forEach(page => page.classList.remove('active'));
  
  // 显示指定页面
  const targetPage = document.getElementById(pageId);
  if (targetPage) {
    targetPage.classList.add('active');
  }
  
  // 更新导航状态
  const navItems = document.querySelectorAll('.nav-item');
  navItems.forEach(item => item.classList.remove('active'));
  
  // 根据页面ID设置对应的导航项为活跃状态
  const navMap = {
    'homePage': 0,
    'recordPage': 1,
    'sportPage': 2,
    'dietPage': 3,
    'exchangePage': 4,
    'profilePage': 5
  };
  
  if (navMap.hasOwnProperty(pageId)) {
    navItems[navMap[pageId]].classList.add('active');
  }
  
  // 根据页面类型渲染内容
  switch(pageId) {
    case 'homePage':
      renderHome();
      break;
    case 'recordPage':
      renderRecord();
      break;
    case 'sportPage':
      renderSport();
      break;
    case 'dietPage':
      renderDiet();
      break;
    case 'exchangePage':
      renderExchange();
      break;
    case 'profilePage':
      renderProfile();
      break;
    case 'historyPage':
      renderHistory();
      break;
  }
}

// 工具函数
function getTodayStr() {
  const d = new Date();
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function formatDateShort(dateStr) {
  const date = new Date(dateStr);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}/${day}`;
}

function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 6) return '夜深了';
  if (hour < 12) return '早上好';
  if (hour < 18) return '下午好';
  return '晚上好';
}

// ===== 体重记录 =====
function getWeightRecords() {
  return JSON.parse(localStorage.getItem('weightRecords') || '[]');
}

function saveWeightRecord(date, weight) {
  let records = getWeightRecords();
  
  // 添加调试信息
  console.log('保存体重记录:', { date, weight, currentTime: new Date().toLocaleString() });
  
  // 如果当天已记录，覆盖
  const idx = records.findIndex(r => r.date === date);
  if (idx >= 0) {
    console.log('更新已存在的记录:', records[idx]);
    records[idx].weight = weight;
  } else {
    console.log('添加新记录');
    records.push({date, weight});
  }
  
  localStorage.setItem('weightRecords', JSON.stringify(records));
  
  // 检查成就
  checkAndRewardAchievements();
}

function getPoints() {
  return parseInt(localStorage.getItem('points') || '0', 10);
}

function setPoints(points) {
  localStorage.setItem('points', points);
}

function getLevel() {
  return parseInt(localStorage.getItem('level') || '1', 10);
}

function setLevel(level) {
  localStorage.setItem('level', level);
}

// 检查并奖励成就
function checkAndRewardAchievements() {
  const data = {
    weightRecords: getWeightRecords(),
    sportRecords: getSportRecords(),
    level: getLevel(),
    points: getPoints()
  };
  
  const unlockedAchievements = JSON.parse(localStorage.getItem('unlockedAchievements') || '[]');
  let totalReward = 0;
  let newAchievements = [];
  
  ACHIEVEMENTS.forEach(achievement => {
    if (!unlockedAchievements.includes(achievement.id) && achievement.condition(data)) {
      unlockedAchievements.push(achievement.id);
      newAchievements.push(achievement);
      totalReward += ACHIEVEMENT_REWARDS[achievement.id] || 0;
    }
  });
  
  if (newAchievements.length > 0) {
    localStorage.setItem('unlockedAchievements', JSON.stringify(unlockedAchievements));
    
    // 添加积分奖励
    if (totalReward > 0) {
      const currentPoints = getPoints();
      setPoints(currentPoints + totalReward);
      
      // 检查是否升级
      const currentLevel = getLevel();
      const newLevel = Math.floor((currentPoints + totalReward) / LEVEL_UP_POINTS) + 1;
      if (newLevel > currentLevel) {
        setLevel(newLevel);
        showToast(`恭喜升级到等级 ${newLevel}！`);
      }
    }
    
    // 显示成就解锁提示
    newAchievements.forEach(achievement => {
      const reward = ACHIEVEMENT_REWARDS[achievement.id] || 0;
      showToast(`🏆 解锁成就：${achievement.title} +${reward}积分`);
    });
  }
}

function updateLevelAndPoints(newWeight) {
  let records = getWeightRecords();
  if (records.length < 2) return; // 没有历史数据不加分
  // 找到上一次体重
  let prev = records
    .filter(r => r.date !== getTodayStr())
    .sort((a, b) => b.date.localeCompare(a.date))[0];
  if (!prev) return;
  let diff = prev.weight - newWeight;
  if (diff > 0) {
    // 体重下降，获得积分
    let addPoints = Math.floor(diff * POINTS_PER_KG);
    if (addPoints > 0) {
      let points = getPoints() + addPoints;
      setPoints(points);
      // 升级
      let level = getLevel();
      let newLevel = Math.floor(points / LEVEL_UP_POINTS) + 1;
      if (newLevel > level) {
        setLevel(newLevel);
        showToast('恭喜升级到等级 ' + newLevel + '！');
      } else {
        showToast('体重下降，获得 ' + addPoints + ' 积分！');
      }
    }
  }
  
  // 检查成就
  checkAndRewardAchievements();
}

// ===== 运动记录 =====
function getSportRecords() {
  let records = JSON.parse(localStorage.getItem('sportRecords') || '[]');
  
  // 数据迁移：处理旧格式的运动记录
  records = records.map(record => {
    if (!record.hasOwnProperty('distance')) {
      record.distance = null;
    }
    if (!record.hasOwnProperty('count')) {
      record.count = null;
    }
    if (!record.hasOwnProperty('intensity')) {
      record.intensity = '中强度';
    }
    if (!record.calories || isNaN(record.calories)) {
      record.calories = 0;
    }
    if (!record.duration || isNaN(record.duration)) {
      record.duration = 0;
    }
    return record;
  });
  
  return records;
}

function saveSportRecord(date, type, duration, distance, count, intensity, calories) {
  let records = getSportRecords();
  records.push({date, type, duration, distance, count, intensity, calories});
  localStorage.setItem('sportRecords', JSON.stringify(records));
  
  // 检查成就
  checkAndRewardAchievements();
}

function getTodaySports() {
  const today = getTodayStr();
  return getSportRecords().filter(r => r.date === today);
}

function getTodayCalories() {
  const todaySports = getTodaySports();
  return todaySports.reduce((total, sport) => total + (sport.calories || 0), 0);
}

// ===== 饮食推荐 =====
const DIET_LIST = [
  {
    breakfast: '燕麦牛奶+鸡蛋+水果',
    lunch: '鸡胸肉+糙米饭+西兰花',
    dinner: '三文鱼+蔬菜沙拉+紫薯'
  },
  {
    breakfast: '全麦面包+酸奶+坚果',
    lunch: '牛肉+藜麦+时蔬',
    dinner: '虾仁+玉米+番茄炒蛋'
  },
  {
    breakfast: '玉米粥+鸡蛋+苹果',
    lunch: '鱼肉+红薯+青菜',
    dinner: '豆腐+西红柿+小米粥'
  },
  {
    breakfast: '杂粮粥+煮蛋+香蕉',
    lunch: '火鸡肉+糙米+蔬菜',
    dinner: '牛油果+鸡蛋+蔬菜色拉'
  }
];

// 一周饮食计划
const WEEKLY_DIET_PLANS = [
  {
    day: '周一',
    icon: '🌅',
    breakfast: '燕麦牛奶+水煮蛋+蓝莓',
    lunch: '鸡胸肉+糙米饭+西兰花+胡萝卜',
    dinner: '三文鱼+蔬菜沙拉+紫薯',
    calories: 1450,
    tips: '周一开启健康一周，蛋白质充足'
  },
  {
    day: '周二',
    icon: '🌤️',
    breakfast: '全麦吐司+酸奶+坚果',
    lunch: '牛肉+藜麦+时蔬+番茄',
    dinner: '虾仁+玉米+番茄炒蛋',
    calories: 1380,
    tips: '周二补充优质脂肪，促进代谢'
  },
  {
    day: '周三',
    icon: '☀️',
    breakfast: '玉米粥+鸡蛋+苹果',
    lunch: '鱼肉+红薯+青菜+豆腐',
    dinner: '豆腐+西红柿+小米粥',
    calories: 1420,
    tips: '周三增加膳食纤维，促进消化'
  },
  {
    day: '周四',
    icon: '🌤️',
    breakfast: '杂粮粥+煮蛋+香蕉',
    lunch: '火鸡肉+糙米+蔬菜+南瓜',
    dinner: '牛油果+鸡蛋+蔬菜色拉',
    calories: 1350,
    tips: '周四补充维生素，增强免疫力'
  },
  {
    day: '周五',
    icon: '🌅',
    breakfast: '希腊酸奶+燕麦+草莓',
    lunch: '鲑鱼+藜麦+芦笋+甜椒',
    dinner: '鸡胸肉+蔬菜汤+红薯',
    calories: 1400,
    tips: '周五补充omega-3，保护心血管'
  },
  {
    day: '周六',
    icon: '🌤️',
    breakfast: '全麦面包+鸡蛋+牛奶',
    lunch: '豆腐+糙米饭+青菜+蘑菇',
    dinner: '虾仁+蔬菜沙拉+玉米',
    calories: 1320,
    tips: '周六清淡饮食，给肠胃休息'
  },
  {
    day: '周日',
    icon: '☀️',
    breakfast: '燕麦粥+坚果+蜂蜜',
    lunch: '鸡胸肉+红薯+西兰花+胡萝卜',
    dinner: '三文鱼+蔬菜汤+小米粥',
    calories: 1380,
    tips: '周日总结一周，准备新开始'
  }
];

const NUTRITION_TIPS = [
  '每天喝够8杯水，帮助新陈代谢',
  '多吃蔬菜水果，补充维生素和纤维',
  '控制碳水摄入，选择全谷物',
  '适量蛋白质，帮助肌肉恢复',
  '少油少盐，清淡饮食更健康',
  '定时定量，规律饮食很重要',
  '细嚼慢咽，帮助消化吸收',
  '晚餐要早，避免睡前进食',
  '多样化饮食，营养更均衡',
  '适量运动，配合饮食效果更好'
];

function getDietIndex() {
  return parseInt(localStorage.getItem('dietIndex') || '0', 10);
}

function setDietIndex(idx) {
  localStorage.setItem('dietIndex', idx);
}

function getCurrentDayIndex() {
  const today = new Date();
  return today.getDay(); // 0是周日，1是周一，以此类推
}

// ===== 页面渲染 =====
function renderHome() {
  // 问候语
  const greeting = getGreeting();
  document.querySelector('.user-greeting h2').textContent = greeting + '！';
  
  // 今日体重
  const today = getTodayStr();
  const records = getWeightRecords();
  const todayRec = records.find(r => r.date === today);
  
  document.getElementById('todayWeight').textContent = todayRec ? todayRec.weight : '--';
  document.getElementById('todayDate').textContent = formatDate(today);
  
  // 体重趋势
  renderWeightTrend(records, todayRec);
  
  // 积分、等级
  document.getElementById('points').textContent = getPoints() + ' 积分';
  document.getElementById('level').textContent = '等级 ' + getLevel();
  
  // 体重曲线
  renderChart(records);
}

function renderWeightTrend(records, todayRec) {
  const trendEl = document.getElementById('weightTrend');
  
  if (!todayRec || records.length < 2) {
    trendEl.innerHTML = '<span class="trend-text">暂无数据</span>';
    return;
  }
  
  // 找到上一次体重
  const prev = records
    .filter(r => r.date !== getTodayStr())
    .sort((a, b) => b.date.localeCompare(a.date))[0];
  
  if (!prev) {
    trendEl.innerHTML = '<span class="trend-text">首次记录</span>';
    return;
  }
  
  const diff = todayRec.weight - prev.weight;
  let trendText, trendClass;
  
  if (diff > 0) {
    trendText = `+${diff.toFixed(1)}kg`;
    trendClass = 'trend-up';
  } else if (diff < 0) {
    trendText = `${diff.toFixed(1)}kg`;
    trendClass = 'trend-down';
  } else {
    trendText = '0kg';
    trendClass = 'trend-stable';
  }
  
  trendEl.innerHTML = `<span class="trend-text ${trendClass}">${trendText}</span>`;
}

function renderRecord() {
  const records = getWeightRecords();
  const historyEl = document.getElementById('weightHistory');
  const countEl = document.getElementById('recordCount');
  
  countEl.textContent = records.length + ' 条记录';
  
  if (records.length === 0) {
    historyEl.innerHTML = '<div class="empty-state"><i class="fas fa-weight"></i><p>暂无记录</p></div>';
    return;
  }
  
  // 显示最近7天记录，显示完整年月日
  const recentRecords = records.slice(-7).reverse();
  historyEl.innerHTML = recentRecords.map(r => 
    `<div class="history-item">
      <span>${formatDate(r.date)}</span>
      <span>${r.weight} kg</span>
    </div>`
  ).join('');
}

function renderSport() {
  const todaySports = getTodaySports();
  const allSports = getSportRecords();
  const todayCalories = getTodayCalories();
  
  // 今日消耗
  document.getElementById('todayCalories').textContent = todayCalories + ' 千卡';
  
  // 今日运动
  const todayEl = document.getElementById('todaySports');
  if (todaySports.length === 0) {
    todayEl.innerHTML = '<div class="empty-state"><i class="fas fa-running"></i><p>今天还没有运动记录</p></div>';
  } else {
    todayEl.innerHTML = todaySports.map(s => {
      const sportConfig = SPORT_TYPES[s.type] || SPORT_TYPES['其他'];
      const icon = sportConfig.icon;
      let details = '';
      
      if (s.count && s.count > 0) {
        details = `${s.count}个`;
      } else if (s.duration && s.duration > 0) {
        details = `${s.duration}分钟`;
      }
      
      if (s.distance && s.distance > 0) details += ` · ${s.distance}km`;
      if (s.intensity && s.intensity !== 'undefined') details += ` · ${s.intensity}`;
      details += ` · ${s.calories || 0}千卡`;
      
      return `<div class="sport-item">
        <span>${icon} ${s.type}</span>
        <span>${details}</span>
      </div>`;
    }).join('');
  }
  
  // 运动历史（最近10条）
  const historyEl = document.getElementById('sportHistory');
  const recentSports = allSports.slice(-10).reverse();
  if (recentSports.length === 0) {
    historyEl.innerHTML = '<div class="empty-state"><i class="fas fa-clock"></i><p>暂无运动记录</p></div>';
  } else {
    historyEl.innerHTML = recentSports.map(s => {
      const sportConfig = SPORT_TYPES[s.type] || SPORT_TYPES['其他'];
      const icon = sportConfig.icon;
      let details = '';
      
      if (s.count && s.count > 0) {
        details = `${s.count}个`;
      } else if (s.duration && s.duration > 0) {
        details = `${s.duration}分钟`;
      }
      
      if (s.distance && s.distance > 0) details += ` · ${s.distance}km`;
      if (s.intensity && s.intensity !== 'undefined') details += ` · ${s.intensity}`;
      details += ` · ${s.calories || 0}千卡`;
      
      return `<div class="sport-item">
        <span>${formatDate(s.date)} ${icon} ${s.type}</span>
        <span>${details}</span>
      </div>`;
    }).join('');
  }
}

function renderDiet() {
  // 计算本周总热量和平均热量
  const totalCalories = WEEKLY_DIET_PLANS.reduce((sum, plan) => sum + plan.calories, 0);
  const avgCalories = Math.round(totalCalories / 7);
  
  // 更新概览统计
  document.getElementById('weeklyCalories').textContent = totalCalories;
  document.getElementById('avgCalories').textContent = avgCalories;
  
  // 获取当前日期，默认显示今天对应的饮食计划
  const currentDayIndex = getCurrentDayIndex();
  const adjustedIndex = currentDayIndex === 0 ? 6 : currentDayIndex - 1; // 转换为数组索引
  
  // 渲染当前天的饮食计划
  renderDietDay(adjustedIndex);
  
  // 更新tab状态
  updateDietTabs(adjustedIndex);
  
  // 营养小贴士
  const tipsEl = document.getElementById('nutritionTips');
  const randomTip = NUTRITION_TIPS[Math.floor(Math.random() * NUTRITION_TIPS.length)];
  tipsEl.textContent = randomTip;
}

// 渲染指定天的饮食计划
function renderDietDay(dayIndex) {
  const plan = WEEKLY_DIET_PLANS[dayIndex];
  if (!plan) return;
  
  // 更新页面标题和提示
  document.getElementById('currentDayName').textContent = plan.day;
  document.getElementById('currentDayTip').textContent = plan.tips;
  document.getElementById('currentDayCalories').textContent = plan.calories;
  
  // 渲染三餐内容
  document.getElementById('breakfastContent').innerHTML = formatMealContent(plan.breakfast);
  document.getElementById('lunchContent').innerHTML = formatMealContent(plan.lunch);
  document.getElementById('dinnerContent').innerHTML = formatMealContent(plan.dinner);
}

// 格式化餐食内容
function formatMealContent(mealText) {
  const items = mealText.split('+');
  return items.map(item => 
    `<div class="food-item">
      <span class="food-name">${item.trim()}</span>
    </div>`
  ).join('');
}

// 切换饮食天数
window.switchDietDay = function(dayIndex, element) {
  // 更新tab状态
  updateDietTabs(dayIndex);
  
  // 渲染对应天的饮食计划
  renderDietDay(dayIndex);
  
  // 添加切换动画效果
  const dietCard = document.querySelector('.diet-card');
  dietCard.style.opacity = '0';
  setTimeout(() => {
    dietCard.style.opacity = '1';
  }, 150);
};

// 更新tab状态
function updateDietTabs(activeIndex) {
  const tabs = document.querySelectorAll('.week-tabs .tab-item');
  tabs.forEach((tab, index) => {
    if (index === activeIndex) {
      tab.classList.add('active');
    } else {
      tab.classList.remove('active');
    }
  });
}

function renderProfile() {
  const points = getPoints();
  const level = getLevel();
  const weightRecords = getWeightRecords();
  const sportRecords = getSportRecords();
  const unlockedAchievements = JSON.parse(localStorage.getItem('unlockedAchievements') || '[]');
  
  // 更新统计数据
  document.getElementById('profileLevel').textContent = `等级 ${level}`;
  document.getElementById('profilePoints').textContent = points;
  document.getElementById('recordDays').textContent = weightRecords.length;
  
  // 成就统计
  const totalAchievements = ACHIEVEMENTS.length;
  const unlockedCount = unlockedAchievements.length;
  const achievementProgress = `${unlockedCount}/${totalAchievements}`;
  const progressPercentage = totalAchievements > 0 ? (unlockedCount / totalAchievements) * 100 : 0;
  
  // 添加成就进度显示
  const achievementStats = document.getElementById('achievementStats');
  const achievementProgressFill = document.getElementById('achievementProgressFill');
  
  if (achievementStats) {
    achievementStats.textContent = achievementProgress;
  }
  
  if (achievementProgressFill) {
    achievementProgressFill.style.width = `${progressPercentage}%`;
  }
  
  // 渲染成就系统
  renderAchievements({
    weightRecords,
    sportRecords,
    level,
    points
  });
}

// 兑换页面相关函数
function renderExchange() {
  const exchangePoints = document.getElementById('exchangePoints');
  exchangePoints.textContent = getPoints();
  renderExchangeItems('all');
}

function renderExchangeItems(category) {
  const itemsGrid = document.getElementById('exchangeItemsGrid');
  
  if (!itemsGrid) {
    return;
  }
  
  const points = getPoints();
  
  let filteredItems = EXCHANGE_ITEMS;
  if (category !== 'all') {
    filteredItems = EXCHANGE_ITEMS.filter(item => item.category === category);
  }
  
  itemsGrid.innerHTML = filteredItems.map(item => {
    const canAfford = points >= item.cost;
    return `
      <div class="exchange-item ${canAfford ? '' : 'disabled'}" onclick="${canAfford ? `confirmExchange('${item.id}')` : ''}">
        <div class="item-icon">
          <i class="${item.icon}"></i>
        </div>
        <div class="item-name">${item.name}</div>
        <div class="item-desc">${item.desc}</div>
        <div class="item-cost ${canAfford ? 'affordable' : ''}">${item.cost} 积分</div>
      </div>
    `;
  }).join('');
}

function switchExchangeCategory(category, element) {
  // 更新标签状态
  document.querySelectorAll('.tab-item').forEach(tab => {
    tab.classList.remove('active');
  });
  element.classList.add('active');
  
  // 渲染对应分类的商品
  renderExchangeItems(category);
}

function showExchangeModal(itemId) {
  const item = EXCHANGE_ITEMS.find(i => i.id === itemId);
  
  const points = getPoints();
  
  if (!item) {
    showToast('商品不存在');
    return;
  }
  
  if (points < item.cost) {
    showToast('积分不足，无法兑换');
    return;
  }
  
  // 设置全局变量
  currentExchangeItemId = itemId;
  
  // 检查DOM元素是否存在
  const confirmItemIcon = document.getElementById('confirmItemIcon');
  const confirmItemName = document.getElementById('confirmItemName');
  const confirmItemDesc = document.getElementById('confirmItemDesc');
  const confirmItemCost = document.getElementById('confirmItemCost');
  const confirmCurrentPoints = document.getElementById('confirmCurrentPoints');
  const exchangeModal = document.getElementById('exchangeModal');
  
  if (!confirmItemIcon || !confirmItemName || !confirmItemDesc || !confirmItemCost || !confirmCurrentPoints || !exchangeModal) {
    showToast('弹窗元素未找到');
    return;
  }
  
  // 填充弹窗信息
  confirmItemIcon.innerHTML = `<i class="${item.icon}"></i>`;
  confirmItemName.textContent = item.name;
  confirmItemDesc.textContent = item.desc;
  confirmItemCost.textContent = item.cost;
  confirmCurrentPoints.textContent = points;
  
  // 显示弹窗
  exchangeModal.classList.add('show');
  
  // 重新绑定确认按钮事件
  const confirmBtn = document.getElementById('confirmExchangeBtn');
  if (confirmBtn) {
    // 移除旧的事件监听器
    confirmBtn.onclick = null;
    // 添加新的事件监听器
    confirmBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      handleConfirmExchange();
    });
    
    // 也保留onclick属性作为备用
    confirmBtn.onclick = function(e) {
      e.preventDefault();
      e.stopPropagation();
      handleConfirmExchange();
    };
  }
  
  // 显示提示消息
  showToast('兑换确认弹窗已显示！请查看屏幕中央');
}

function confirmExchange(itemId) {
  const item = EXCHANGE_ITEMS.find(i => i.id === itemId);
  
  const points = getPoints();
  
  if (!item) {
    showToast('商品不存在');
    return;
  }
  
  if (points < item.cost) {
    showToast('积分不足，无法兑换');
    return;
  }
  
  // 扣除积分
  const newPoints = points - item.cost;
  setPoints(newPoints);
  
  // 记录兑换历史
  const exchangeHistory = JSON.parse(localStorage.getItem('exchangeHistory') || '[]');
  
  const newRecord = {
    itemId: itemId,
    itemName: item.name,
    cost: item.cost,
    date: new Date().toISOString().slice(0, 10)
  };
  exchangeHistory.push(newRecord);
  localStorage.setItem('exchangeHistory', JSON.stringify(exchangeHistory));
  
  // 关闭弹窗
  const exchangeModal = document.getElementById('exchangeModal');
  if (exchangeModal) {
    exchangeModal.classList.remove('show');
  }
  
  // 更新所有页面的积分显示
  renderExchange();
  renderHome();
  renderProfile();
  
  // 显示成功提示和积分变化
  showToast(`🎉 成功兑换：${item.name}`);
  showToast(`积分变化：${points} → ${newPoints} (-${item.cost})`);
}

function renderAchievements(data) {
  const achievementList = document.getElementById('achievementList');
  const unlockedAchievements = JSON.parse(localStorage.getItem('unlockedAchievements') || '[]');
  
  achievementList.innerHTML = ACHIEVEMENTS.map(achievement => {
    const isUnlocked = unlockedAchievements.includes(achievement.id);
    const reward = ACHIEVEMENT_REWARDS[achievement.id] || 0;
    return `
      <div class="achievement-item ${isUnlocked ? 'unlocked' : ''}">
        <div class="achievement-icon">
          <i class="${achievement.icon}"></i>
        </div>
        <div class="achievement-info">
          <div class="achievement-title">${achievement.title}</div>
          <div class="achievement-desc">${achievement.desc}</div>
          ${reward > 0 ? `<div class="achievement-reward">+${reward}积分</div>` : ''}
        </div>
      </div>
    `;
  }).join('');
}

function renderChart(records) {
  const canvas = document.getElementById('weightChart');
  const ctx = canvas.getContext('2d');
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  if (records.length < 2) {
    ctx.fillStyle = '#bbb';
    ctx.font = '16px sans-serif';
    ctx.fillText('暂无足够数据', 20, canvas.height / 2);
    return;
  }
  
  // 取最近7天
  let recs = records.slice(-7);
  let minW = Math.min(...recs.map(r => r.weight));
  let maxW = Math.max(...recs.map(r => r.weight));
  let gap = maxW - minW;
  let padding = 24;
  let w = canvas.width - padding * 2;
  let h = canvas.height - padding * 2;
  
  // 画线
  ctx.strokeStyle = '#667eea';
  ctx.lineWidth = 2;
  ctx.beginPath();
  recs.forEach((r, i) => {
    let x = padding + (w / (recs.length - 1)) * i;
    let y = padding + h - ((r.weight - minW) / (gap === 0 ? 1 : gap)) * h;
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  });
  ctx.stroke();
  
  // 画点
  ctx.fillStyle = '#667eea';
  recs.forEach((r, i) => {
    let x = padding + (w / (recs.length - 1)) * i;
    let y = padding + h - ((r.weight - minW) / (gap === 0 ? 1 : gap)) * h;
    ctx.beginPath();
    ctx.arc(x, y, 4, 0, 2 * Math.PI);
    ctx.fill();
  });
  
  // 日期
  ctx.fillStyle = '#888';
  ctx.font = '12px sans-serif';
  recs.forEach((r, i) => {
    let x = padding + (w / (recs.length - 1)) * i;
    ctx.fillText(r.date.slice(5), x - 12, canvas.height - 4);
  });
}

// ===== 事件绑定 =====
document.addEventListener('DOMContentLoaded', function() {
  // 启动开屏动画
  initSplashScreen();
  
  // 体重记录
  const saveWeightBtn = document.getElementById('saveWeightBtn');
  const weightInput = document.getElementById('weightInput');
  
  saveWeightBtn.onclick = () => {
    let val = parseFloat(weightInput.value);
    if (!val || val < 20 || val > 300) {
      showToast('请输入合理的体重');
      return;
    }
    const today = getTodayStr();
    console.log('体重录入 - 当前日期:', today, '当前时间:', new Date().toLocaleString());
    saveWeightRecord(today, val);
    updateLevelAndPoints(val);
    weightInput.value = '';
    renderRecord();
    showToast('体重记录已保存');
  };
  
  // 运动记录
  const addSportBtn = document.getElementById('addSportBtn');
  const sportModal = document.getElementById('sportModal');
  const saveSportBtn = document.getElementById('saveSportBtn');
  const closeSportModalBtn = document.getElementById('closeSportModalBtn');
  const closeSportModalBtn2 = document.getElementById('closeSportModalBtn2');
  const sportType = document.getElementById('sportType');
  const sportDistance = document.getElementById('sportDistance');
  const sportCount = document.getElementById('sportCount');
  const sportDuration = document.getElementById('sportDuration');
  const sportIntensity = document.getElementById('sportIntensity');
  const sportCalories = document.getElementById('sportCalories');
  const sportDistanceGroup = document.getElementById('sportDistanceGroup');
  const sportCountGroup = document.getElementById('sportCountGroup');
  const sportIntensityGroup = document.getElementById('sportIntensityGroup');
  
  // 运动类型变化时动态显示/隐藏字段
  sportType.onchange = () => {
    const selectedType = sportType.value;
    const sportConfig = SPORT_TYPES[selectedType];
    
    // 显示/隐藏距离字段
    if (sportConfig.hasDistance) {
      sportDistanceGroup.style.display = 'block';
    } else {
      sportDistanceGroup.style.display = 'none';
      sportDistance.value = '';
    }
    
    // 显示/隐藏计数字段
    if (sportConfig.hasCount) {
      sportCountGroup.style.display = 'block';
    } else {
      sportCountGroup.style.display = 'none';
      sportCount.value = '';
    }
    
    // 显示/隐藏强度字段
    if (sportConfig.hasIntensity) {
      sportIntensityGroup.style.display = 'block';
    } else {
      sportIntensityGroup.style.display = 'none';
      sportIntensity.value = '中强度';
    }
    
    // 自动计算热量
    calculateCalories();
  };
  
  // 时长、个数或强度变化时自动计算热量
  sportDuration.oninput = calculateCalories;
  sportCount.oninput = calculateCalories;
  sportIntensity.onchange = calculateCalories;
  
  function calculateCalories() {
    const selectedType = sportType.value;
    const duration = parseInt(sportDuration.value, 10);
    const count = parseInt(sportCount.value, 10);
    const intensity = sportIntensity.value || '中强度';
    const sportConfig = SPORT_TYPES[selectedType];
    
    if (sportConfig && sportConfig.calorieRate) {
      let calculatedCalories = 0;
      
      if (sportConfig.hasCount && count && count > 0) {
        // 计数类运动：根据个数和强度计算
        const rate = sportConfig.calorieRate[intensity] || sportConfig.calorieRate['中强度'];
        calculatedCalories = Math.round(count * rate * 0.5); // 每个动作消耗的热量
      } else if (duration && duration > 0) {
        // 时长类运动：根据时长和强度计算
        const rate = sportConfig.calorieRate[intensity] || sportConfig.calorieRate['中强度'];
        calculatedCalories = Math.round(duration * rate);
      }
      
      if (!isNaN(calculatedCalories) && calculatedCalories > 0) {
        sportCalories.value = calculatedCalories;
      } else {
        sportCalories.value = '';
      }
    } else {
      sportCalories.value = '';
    }
  }
  
  addSportBtn.onclick = () => {
    sportModal.classList.add('show');
    sportType.value = '跑步';
    sportDistance.value = '';
    sportCount.value = '';
    sportDuration.value = '';
    sportIntensity.value = '中强度';
    sportCalories.value = '';
    sportDistanceGroup.style.display = 'block';
    sportCountGroup.style.display = 'none';
    sportIntensityGroup.style.display = 'block';
    sportType.focus();
  };
  
  closeSportModalBtn.onclick = () => {
    sportModal.classList.remove('show');
  };
  
  closeSportModalBtn2.onclick = () => {
    sportModal.classList.remove('show');
  };
  
  // 兑换弹窗相关
  const exchangeModal = document.getElementById('exchangeModal');
  const closeExchangeModalBtn = document.getElementById('closeExchangeModalBtn');
  const cancelExchangeBtn = document.getElementById('cancelExchangeBtn');
  
  closeExchangeModalBtn.onclick = () => {
    exchangeModal.classList.remove('show');
  };
  
  cancelExchangeBtn.onclick = () => {
    exchangeModal.classList.remove('show');
  };
  

  
  saveSportBtn.onclick = () => {
    let type = sportType.value;
    let distance = parseFloat(sportDistance.value) || null;
    let count = parseInt(sportCount.value, 10) || null;
    let duration = parseInt(sportDuration.value, 10);
    let intensity = sportIntensity.value || '中强度';
    let calories = parseInt(sportCalories.value, 10);
    
    if (!type || !calories) {
      showToast('请填写完整运动信息');
      return;
    }
    
    const sportConfig = SPORT_TYPES[type];
    
    // 验证必填字段
    if (sportConfig.hasDistance && !distance) {
      showToast('请输入运动距离');
      return;
    }
    
    if (sportConfig.hasCount && !count) {
      showToast('请输入运动个数');
      return;
    }
    
    if (!sportConfig.hasCount && !duration) {
      showToast('请输入运动时长');
      return;
    }
    
    // 确保所有字段都有有效值
    const record = {
      date: getTodayStr(),
      type: type,
      duration: duration || 0,
      distance: distance || null,
      count: count || null,
      intensity: intensity || '中强度',
      calories: calories || 0
    };
    
    saveSportRecord(record.date, record.type, record.duration, record.distance, record.count, record.intensity, record.calories);
    sportModal.classList.remove('show');
    renderSport();
    showToast('运动记录已保存');
  };
  
  // 饮食推荐
  const changeDietBtn = document.getElementById('changeDietBtn');
  changeDietBtn.onclick = () => {
    let idx = getDietIndex();
    idx = (idx + 1) % DIET_LIST.length;
    setDietIndex(idx);
    renderDiet();
  };
});

// 消息队列管理
let toastQueue = [];
let isShowingToast = false;

function showToast(msg) {
  // 将消息添加到队列
  toastQueue.push(msg);
  
  // 如果没有正在显示的消息，开始显示
  if (!isShowingToast) {
    showNextToast();
  }
}

function showNextToast() {
  if (toastQueue.length === 0) {
    isShowingToast = false;
    return;
  }
  
  isShowingToast = true;
  const msg = toastQueue.shift();
  
  let toast = document.createElement('div');
  toast.className = 'toast-message';
  toast.textContent = msg;
  
  document.body.appendChild(toast);
  
  // 淡入效果
  setTimeout(() => {
    toast.classList.add('show');
  }, 10);
  
  // 显示2秒后淡出
  setTimeout(() => {
    toast.classList.add('hide');
    setTimeout(() => {
      toast.remove();
      // 显示下一个消息
      showNextToast();
    }, 300);
  }, 2000);
}

function renderHistory() {
  const exchangeHistory = JSON.parse(localStorage.getItem('exchangeHistory') || '[]');
  const historyList = document.getElementById('exchangeHistoryList');
  
  if (!historyList) {
    return;
  }
  
  if (exchangeHistory.length === 0) {
    historyList.innerHTML = `
      <div class="empty-history">
        <i class="fas fa-gift"></i>
        <p>暂无领取记录</p>
      </div>
    `;
  } else {
    // 按日期倒序排列
    const sortedHistory = exchangeHistory.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 计算总兑换积分
    const totalExchanged = exchangeHistory.reduce((sum, record) => sum + record.cost, 0);
    
    // 添加统计信息
    const statsHtml = `
      <div class="history-stats">
        <div class="stat-item">
          <span>总兑换次数：</span>
          <span class="stat-value">${exchangeHistory.length}</span>
        </div>
        <div class="stat-item">
          <span>总消耗积分：</span>
          <span class="stat-value cost">${totalExchanged}</span>
        </div>
      </div>
    `;
    
    const itemsHtml = sortedHistory.map(record => {
      const item = EXCHANGE_ITEMS.find(i => i.id === record.itemId);
      const icon = item ? item.icon : 'fas fa-gift';
      
      return `
        <div class="exchange-history-item">
          <div class="history-item-icon">
            <i class="${icon}"></i>
          </div>
          <div class="history-item-info">
            <div class="history-item-name">${record.itemName}</div>
            <div class="history-item-date">${formatDate(record.date)}</div>
          </div>
          <div class="history-item-cost">-${record.cost} 积分</div>
        </div>
      `;
    }).join('');
    
    historyList.innerHTML = statsHtml + itemsHtml;
  }
} 